<?php

namespace App\Libraries;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;

class BaiduQianfan
{
    public function run($messages)
    {
        try {
            $headers = [
                'Content-Type' => 'application/json'
            ];
            // 请求参数
            $body = json_encode([
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $messages
                    ]
                ]
            ]);

            $client = new Client([
                'timeout'  => 120, // 设置请求超时时间为10秒
                'connect_timeout' => 10, // 设置连接超时时间为5秒
            ]);
            $access_token = $this->getAccessToken();
            $uri = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' . $access_token;
            $response = $client->post($uri, [
                'headers' => $headers,
                'body' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }
            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException $e) {
            dd($e->getMessage());
        } catch (ConnectException $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken()
    {
        try {
            // 请求参数
            $body = [
                'grant_type' => 'client_credentials',
                'client_id' => env('QIANFAN_API_KEY'),
                'client_secret' => env('QIANFAN_SECRET_KEY')
            ];

            $client = new Client([
                'timeout'  => 120, // 设置请求超时时间为10秒
                'connect_timeout' => 5, // 设置连接超时时间为5秒
            ]);
            $response = $client->post('https://aip.baidubce.com/oauth/2.0/token', [
                'form_params' => $body
            ]);
            if ($response->getStatusCode() != 200) {
                return false;
            }
            $result = json_decode($response->getBody()->getContents(), true);
            return $result['access_token'];
        } catch (RequestException $e) {
            dd($e->getMessage());
        } catch (ConnectException $e) {
            dd($e->getMessage());
        }
    }
}
